<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 教师课程展示管理
 *
 * @icon fa fa-circle-o
 */
class TeacherCourseDisplay extends Backend
{

    /**
     * TeacherCourseDisplay模型对象
     * @var \app\admin\model\TeacherCourseDisplay
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\TeacherCourseDisplay;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            // 传递user_id和teacher_detail_id参数到视图
            $user_id = $this->request->get('user_id', 0);
            $teacher_detail_id = $this->request->get('teacher_detail_id', 0);
            $this->view->assign('user_id', $user_id);
            $this->view->assign('teacher_detail_id', $teacher_detail_id);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        
        // 如果传递了user_id参数，添加过滤条件
        $user_id = $this->request->get('user_id', 0);
        $where_user = '1=1';
        if ($user_id) {
            $where_user = "user_id = {$user_id}";
        }
        
        // 如果传递了teacher_detail_id参数，添加过滤条件
        $teacher_detail_id = $this->request->get('teacher_detail_id', 0);
        $where_teacher_detail = '1=1';
        if ($teacher_detail_id) {
            $where_teacher_detail = "teacher_detail_id = {$teacher_detail_id}";
        }
        
        $list = $this->model->with([
            'user' => function ($query) {
                $query->withField('nickname');
            }]);
        $list = $list->where($where)->where($where_user)->where($where_teacher_detail)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            // 传递teacher_detail_id参数到视图
            $teacher_detail_id = $this->request->get('teacher_detail_id', 0);
            $this->view->assign('teacher_detail_id', $teacher_detail_id);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            
            // 如果URL参数中有teacher_detail_id，直接使用
            $teacher_detail_id = $this->request->get('teacher_detail_id', 0);
            if ($teacher_detail_id) {
                $params['teacher_detail_id'] = $teacher_detail_id;
            } elseif (isset($params['user_id']) && $params['user_id']) {
                // 如果没有teacher_detail_id，但有user_id，则通过user_id查询
                // user_id -> IdentityInfo (where user_id and identity_type='教师') -> IdentityInfo.id (info_id)
                // IdentityInfo.id -> TeacherDetail (where info_id) -> 取第一个匹配的teacher_detail_id
                $identityInfo = \app\admin\model\IdentityInfo::where(['user_id' => $params['user_id'], 'identity_type' => '教师'])->find();
                if ($identityInfo && $identityInfo['id']) {
                    $teacherDetail = \app\admin\model\TeacherDetail::where('info_id', $identityInfo['id'])->find();
                    if ($teacherDetail && $teacherDetail['id']) {
                        $params['teacher_detail_id'] = $teacherDetail['id'];
                    }
                }
            }
            
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

}
